document.addEventListener('DOMContentLoaded', () => {
    // DOM元素
    // 获取所有需要的DOM元素
    const loginPanel = document.getElementById('loginPanel'); // 登录面板
    const mainChat = document.getElementById('mainChat'); // 主聊天界面
    const usernameInput = document.getElementById('usernameInput'); // 用户名输入框
    const loginButton = document.getElementById('loginButton'); // 登录按钮
    const userListItems = document.getElementById('userListItems'); // 用户列表容器
    const currentUserAvatar = document.getElementById('currentUserAvatar'); // 当前用户头像
    const currentUserName = document.getElementById('currentUserName'); // 当前用户名显示
    const chatMessages = document.getElementById('chatMessages'); // 聊天消息显示区域
    const messageInput = document.getElementById('messageInput'); // 消息输入框
    const sendButton = document.getElementById('sendButton'); // 发送按钮
    const chatInput = document.getElementById('chatInput'); // 聊天输入区域
    const currentChatTitle = document.getElementById('currentChatTitle'); // 当前聊天标题
    const chatPartnerAvatar = document.getElementById('chatPartnerAvatar'); // 聊天对方头像
    const chatPartnerStatus = document.getElementById('chatPartnerStatus'); // 聊天对方状态
    const backButton = document.getElementById('backButton'); // 返回按钮(移动端)
    
        let ws; // WebSocket 连接对象
    let currentUser = { // 当前用户信息
        id: null, // 用户ID
        name: null, // 用户名
        avatar: null // 头像URL
    };
    let currentChatUserId = null; // 当前聊天对象的用户ID
    let messageHistory = {}; // 消息历史记录，格式: {userId: {messages: [], unread: boolean}}
    // 1. 登录功能
    // 登录按钮点击事件
loginButton.addEventListener('click', connectWebSocket);

function connectWebSocket() {
    const username = usernameInput.value.trim();
    if (!username) {
        alert("Please enter your name");
        return;
    }
    
    // 生成随机用户ID和头像
    currentUser.id = generateUserId();
    currentUser.name = username;
    currentUser.avatar = `https://api.dicebear.com/7.x/miniavs/svg?seed=${currentUser.id}`;

    console.log('currentUser:',currentUser);

    // 建立WebSocket连接
    ws = new WebSocket(`ws://${window.location.host}/ws`);

    console.log('ws://',ws);

    // WebSocket打开事件
    ws.onopen = () => {
        console.log("WebSocket connected");
        // 发送注册消息
        ws.send(JSON.stringify({
            type: "register",
            user_id: currentUser.id,
            name: currentUser.name,
            avatar: currentUser.avatar
        }));
        
        // 更新UI显示
        loginPanel.classList.add('hidden');
        mainChat.classList.remove('hidden');
        currentUserAvatar.src = currentUser.avatar;
        currentUserName.textContent = currentUser.name;
    };
    
    // WebSocket消息接收事件
    ws.onmessage = (event) => {
        const data = JSON.parse(event.data);

        console.log("Received(data):", data);
        
        // 根据消息类型处理
        switch(data.type) {
            case "users": // 用户列表更新
                updateUserList(data.users);
                break;
            case "message": // 收到消息
                handleIncomingMessage(data);
                break;
            case "user_status": // 用户状态更新
                updateUserStatus(data.user_id, data.status);
                break;
        }
    };
    
    // WebSocket错误事件
    ws.onerror = (error) => {
        console.error("WebSocket error:", error);
        alert("Connection error, please refresh");
    };
    
    // WebSocket关闭事件
    ws.onclose = () => {
        console.log("WebSocket disconnected");
        // 尝试重新连接
        setTimeout(() => {
            alert("Disconnected from server. Trying to reconnect...");
            connectWebSocket();
        }, 1000);
    };
}
    
    // 2. 用户列表功能
    function updateUserList(users) {

    console.log("updateUserList(users):", users);
    console.log("users.length:", users.length);

    // 如果没有其他用户在线
    if (users.length === 0) {
        userListItems.innerHTML = '<div class="no-users">No other users online</div>';
        return;
    }
    
    // 过滤掉当前用户并生成用户列表HTML
    userListItems.innerHTML = users
        .filter(user => user.id !== currentUser.id)
        .map(user => `
            <div class="user-item ${messageHistory[user.id]?.unread ? 'has-new-message' : ''}" 
                 data-user-id="${user.id}">
                <img src="${user.avatar}" alt="${user.name}" class="user-avatar">
                <div class="user-info">
                    <div class="user-name">${user.name}</div>
                    <div class="user-id">ID: ${user.id}</div>
                </div>
                <span class="status ${user.status || 'offline'}">•</span>
            </div>
        `).join('');
        // 为每个用户项添加点击事件
    document.querySelectorAll('.user-item').forEach(item => {
        item.addEventListener('click', () => {
            const userId = item.getAttribute('data-user-id');

            console.log("点击的  userId  为:", userId);

            startChatWithUser(userId);
        });
    });
}
    
    // 3. 聊天功能
    function startChatWithUser(userId) {

    console.log("startChatWithUser(userId):", userId);
    
    currentChatUserId = userId;
    const user = getUserFromList(userId);
    /*在下面就只有name、avatar和status被调用
    return {
        id: userId,
        name: userItem.querySelector('.user-name').textContent,
        avatar: userItem.querySelector('img').src,
        status: userItem.querySelector('.status').classList.contains('online') ? 'online' : 'offline'
    };
     */
    // 更新聊天界面UI
    console.log("user:", user);

    chatInput.classList.remove('hidden');
    messageInput.disabled = false;
    sendButton.disabled = false;
    currentChatTitle.textContent = user.name;
    chatPartnerAvatar.src = user.avatar;
    chatPartnerStatus.className = `status ${user.status || 'offline'}`;
    
    // 显示与该用户的消息历史
    displayMessageHistory(userId);
    
    // 标记为已读
    if (messageHistory[userId]) {
        messageHistory[userId].unread = false;
    }
    
    // 移动端处理 - 显示聊天区域，隐藏用户列表
    if (window.innerWidth <= 768) {
        document.querySelector('.user-list').classList.add('hidden');
        document.querySelector('.chat-area').classList.add('active');
        backButton.classList.remove('hidden');
    }
}
    
    // 4. 消息处理
    function handleIncomingMessage(data) {
    const fromUserId = data.from;
    
    console.log("handleIncomingMessage(data)收到的数据:", data);
    // 初始化该用户的消息历史记录
    if (!messageHistory[fromUserId]) {
        messageHistory[fromUserId] = {
            messages: [],
            unread: false
        };
    }
    
    // 存储消息
    messageHistory[fromUserId].messages.push({
        content: data.content,
        timestamp: data.timestamp,
        from: data.from,
        to: data.to
    });
    
    // 如果消息来自当前聊天用户，直接显示
    if (fromUserId === currentChatUserId) {
        displayMessage(data);
    } else {
        // 否则标记为未读
        messageHistory[fromUserId].unread = true;
        updateUserList(getOnlineUsers());
    }
}

function displayMessage(data) {
    const isCurrentUser = data.from === currentUser.id;
    const messageElement = document.createElement('div');
    messageElement.className = `message ${isCurrentUser ? 'sent' : 'received'}`;
    
    // 格式化时间
    const time = new Date(data.timestamp || Date.now());
    const timeString = time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    
    // 构建消息HTML
    messageElement.innerHTML = `
        <div class="message-content">${data.content}</div>
        <div class="message-time">${timeString}</div>
    `;
    
    // 添加到聊天区域并滚动到底部
    chatMessages.appendChild(messageElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function displayMessageHistory(userId) {
    chatMessages.innerHTML = '';
    
    // 如果没有消息历史，显示提示
    if (!messageHistory[userId] || messageHistory[userId].messages.length === 0) {
        chatMessages.innerHTML = `
            <div class="no-messages">
                No messages yet. Start the conversation!
            </div>
        `;
        return;
    }
    
    // 显示所有历史消息
    messageHistory[userId].messages.forEach(msg => {
        displayMessage(msg);
    });
}
    
    // 5. 发送消息
    // 发送按钮点击事件
sendButton.addEventListener('click', sendMessage);

// 输入框回车事件
messageInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

function sendMessage() {
    const content = messageInput.value.trim();
    if (!content || !currentChatUserId) return;
    
    // 构建消息对象
    const message = {
        type: "message",
        from: currentUser.id,
        to: currentChatUserId,
        content: content,
        timestamp: Date.now()
    };
    
    // 发送消息
    ws.send(JSON.stringify(message));
    
    // 初始化该用户的消息历史记录
    if (!messageHistory[currentChatUserId]) {
        messageHistory[currentChatUserId] = {
            messages: [],
            unread: false
        };
    }
    
    // 存储消息到本地历史
    messageHistory[currentChatUserId].messages.push({
        ...message,
        from: currentUser.id
    });
    
    // 显示消息并清空输入框
    displayMessage(message);
    messageInput.value = "";
}
    
    // 6. 辅助函数
    // 生成随机用户ID
function generateUserId() {
    return 'user-' + Math.random().toString(36).substr(2, 9);
}

// 从用户列表中获取用户信息
function getUserFromList(userId) {
    const userItem = document.querySelector(`.user-item[data-user-id="${userId}"]`);
    if (!userItem) return null;
    
    return {
        id: userId,
        name: userItem.querySelector('.user-name').textContent,
        avatar: userItem.querySelector('img').src,
        status: userItem.querySelector('.status').classList.contains('online') ? 'online' : 'offline'
    };
}

// 获取所有在线用户
function getOnlineUsers() {
    const items = document.querySelectorAll('.user-item');
    return Array.from(items).map(item => ({
        id: item.getAttribute('data-user-id'),
        name: item.querySelector('.user-name').textContent,
        avatar: item.querySelector('img').src,
        status: item.querySelector('.status').classList.contains('online') ? 'online' : 'offline'
    }));
}

// 更新用户状态
function updateUserStatus(userId, status) {
    const userItem = document.querySelector(`.user-item[data-user-id="${userId}"]`);
    if (userItem) {
        const statusElement = userItem.querySelector('.status');
        statusElement.className = `status ${status}`;
        
        // 如果正在与该用户聊天，也更新聊天界面的状态显示
        if (userId === currentChatUserId) {
            chatPartnerStatus.className = `status ${status}`;
        }
    }
}
    
    // 7. 返回按钮处理
    // 返回按钮点击事件
backButton.addEventListener('click', () => {
    document.querySelector('.user-list').classList.remove('hidden');
    document.querySelector('.chat-area').classList.remove('active');
    backButton.classList.add('hidden');
});

// 窗口大小变化事件 - 响应式设计处理
window.addEventListener('resize', () => {
    if (window.innerWidth > 768) {
        document.querySelector('.user-list').classList.remove('hidden');
        document.querySelector('.chat-area').classList.remove('hidden');
        backButton.classList.add('hidden');
    }
});
});